package com.ruoyi.api.daoru;

import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;


import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class ImportService {

    @Autowired
    private ImportUtils importUtils;

    public ImportResult validateAndImport(MultipartFile file) {
        return importUtils.importData(file, User.class, this::validateUser, this::batchInsertUsers);
    }

    // 数据校验方法
    private List<String> validateUser(User user, int rowIndex) {
        List<String> errors = new ArrayList<>();

        if (StringUtils.isEmpty(user.getUsername())) {
            errors.add("用户名不能为空");
        }
        if (user.getAge() == null || user.getAge() <= 0) {
            errors.add("年龄必须为正数");
        }
        if (!User.Status.isValidCode(user.getStatus())) {
            errors.add("无效的状态值");
        }

        return errors.stream()
                .map(msg -> "第" + rowIndex + "行：" + msg)
                .collect(Collectors.toList());
    }

    // 数据保存方法
    @Transactional
    public Void batchInsertUsers(List<User> userList) {
        for (User user : userList) {
            System.out.println("用户========" + user);
        }
        return null;
    }
}
